using AutoMapper;
using Coldairarrow.Business;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Util;
using EFCore.Sharding;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.SubApp
{
    public class DepartmentSyncBusiness : BaseBusiness<Base_Department>, IDepartmentSyncBusiness, ITransientDependency
    {
        readonly IMapper _mapper;
        public DepartmentSyncBusiness(
            IDbAccessor db,
            IMapper mapper
            )
            : base(db)
        {
            _mapper = mapper;
        }


        #region 外部接口
        [DataRepeatValidate(new string[] { "Name" }, new string[] { "部门名" })]
       
        [Transactional]
        public async Task AddDataAsync(DepartmentSyncInputDTO input)
        {
            await InsertAsync(_mapper.Map<Base_Department>(input));
            await WriteLog(UserLogType.部门管理, "添加部门：" + input.Name);
        }


        [DataRepeatValidate(new string[] { "Name" }, new string[] { "部门名" })]
        
        [Transactional]
        public async Task UpdateDataAsync(DepartmentSyncInputDTO input)
        {
            await UpdateAsync(_mapper.Map<Base_Department>(input));
            await WriteLog(UserLogType.部门管理, "修改部门：" + input.Name);

        }

        [Transactional]
        public async Task DeleteDataAsync(List<string> ids)
        {

            if (await GetIQueryable().AnyAsync(x => ids.Contains(x.ParentId)))
                throw new BusException("禁止删除！请先删除所有子级！");

            List<Base_Department> departments = new List<Base_Department>();
            ids.ForEach(id => {
                var department = Service.GetEntity<Base_Department>(id);
                if(department != null)
                {
                    departments.Add(department);
                }
            });
            await DeleteAsync(ids);
            var names = string.Join(",", departments.Select(x => x.Name).ToList());
            await WriteLog(UserLogType.部门管理, "删除部门：" + names);
        }

        [Transactional]
        public async Task<List<string>> GetAllDataAsync()
        {
           return await GetIQueryable().Select(x => x.Id).ToListAsync();
        }
        public bool CheckExists(string id)
        {
            List<string> ids = new List<string>();
            ids.Add(id);
            var user = Service.GetEntity<Base_Department>(id);
            if (user == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


        /// <summary>
        /// 取得角色列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<RoleDTo>> GetRoleListAsync()
        {
            var q = Service.GetIQueryable<Base_Role>().Select(x => new RoleDTo { Id = x.Id, RoleName = x.RoleName });
            return await q.ToListAsync();
        }
        #endregion

        #region 私有成员
        private async Task WriteLog(UserLogType userLogType, string msg)
        {
            var log = new Base_UserLog
            {
                Id = IdHelper.GetId(),
                CreateTime = DateTime.Now,
                CreatorId = string.Empty,
                CreatorRealName = "远程数据同步",
                LogContent = msg,
                LogType = userLogType.ToString()
            };
            await Service.InsertAsync(log);
        }

        private async Task SetUserRoleAsync(string userId, List<string> roleIds)
        {
            roleIds = roleIds ?? new List<string>();
            var userRoleList = roleIds.Select(x => new Base_UserRole
            {
                Id = IdHelper.GetId(),
                CreateTime = DateTime.Now,
                UserId = userId,
                RoleId = x
            }).ToList();
            await Service.DeleteAsync<Base_UserRole>(x => x.UserId == userId);
            await Service.InsertAsync(userRoleList);
        }
        #endregion
    }
}